package cn.itcast.order.service;

import cn.itcast.feign.clients.UserClient;
import cn.itcast.feign.pojo.User;
import cn.itcast.order.mapper.OrderMapper;
import cn.itcast.order.pojo.Order;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

@Service
public class OrderService {


    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private UserClient userClient;
    @Autowired
    private OrderMapper orderMapper;

    public Order queryOrderFeign(Long id) {
        Order order = queryOrderId(id);
        if (Objects.nonNull(order)) {
            //使用FeignClient发起http请求，查询用户
            User user = userClient.findById(order.getUserId());
            order.setUser(user);
        }
        return order;
    }

    public Order queryOrderRestTemplate(Long id) {
        Order order = generateOrder(id);
        //利用RestTemplate发起http请求，查询用户
        String restUrl = "http://localhost:8081/user/" + id;
        String registerUrl = "http://user-service/user/" + id;
        User user = restTemplate.getForObject(registerUrl, User.class);
        order.setUser(user);
        return order;
    }


    public Order queryOrderId(Long orderId) {
        return orderMapper.findById(orderId);
    }

    private Order generateOrder(Long id) {
        Order order = new Order();
        order.setId(id);
        order.setNum(Math.toIntExact(id));
        order.setPrice(id);
        order.setName("测试订单");
        order.setUserId(id);
        return order;
    }
}
